createRenderJob
- ๐ฌ๐ง English
- ๐ฎ๐น Italian
Function Name: createRenderJob
Author: Gabriele Gilio Creation Date: 25/09/2025
Last Reviewer: Gabriele Gilio
Trigger: HTTPS (onRequest)
Purpose: Handles the creation of 3D thumbnail rendering jobs by validating requests, saving them to Firestore, and queueing them via Google Cloud Tasks for asynchronous processing.
Detailed Functionalityโ
This Firebase Function manages the complete workflow for 3D thumbnail rendering requests through an asynchronous processing architecture:
1. REQUEST VALIDATION AND CORS HANDLINGโ
- Accepts POST requests with CORS support for frontend calls
- Validates required parameters: modelId, templateId, imageWidth, imageHeight
- Optional parameters: reflect (boolean as string), noShadows (boolean as string)
- Returns 400 Bad Request for missing required parameters
- Returns 405 Method Not Allowed for non-POST requests
2. JOB ID GENERATION AND FIRESTORE STORAGEโ
- Generates unique job ID using UUID v4
- Creates document in 'RenderingJobs' collection with:
- status: "queued"
- createdAt: ISO timestamp
- modelId: provided model ID
- templateId: provided template ID
- imageWidth: provided width
- imageHeight: provided height
- CRITICAL: If Firestore save fails, execution is immediately terminated with 500 error
- Returns error message: "Unable to save the rendering job in the database. Try again later."
- Logs job creation details for debugging and monitoring
3. TEMPLATE CONFIGURATION RETRIEVALโ
- Retrieves template document from 'RenderingTemplates' collection using templateId
- Returns 404 error if template not found
- Extracts and transforms template data into worker format:
- camera_fov: from fieldOfView
- camera_position: from cameraPosition
- camera_rotation: from cameraRotation
- camera_look_at: from cameraLookAt
- view_name: from viewName
- light_exposition: from lightExposition (default: 1)
4. PAYLOAD PREPARATIONโ
- Creates base payload with: modelId, templateConfig, outputWidth, outputHeight, jobId, frontendUrl
- Conditionally adds reflect and noShadows parameters if provided
- Sets frontendUrl to staging environment: "https://ars-renderer-staging.web.app/Renderer"
5. ENVIRONMENT-SPECIFIC PROCESSINGโ
Development Environment (Local Emulator):
- Makes direct HTTP request to local worker at "http://127.0.0.1:8080/process-render"
- Uses axios for immediate processing without queueing
- Provides immediate feedback on worker response
- Returns error if HTTP request fails
Production Environment (Staging/Production):
- Creates Google Cloud Tasks task for asynchronous processing
- Queues task in 'thumbnail-render-queue' in 'europe-central2' region
- Schedules task execution 5 seconds after creation
- Worker URL:
- Base64 encodes payload for Cloud Tasks transmission
6. CLOUD TASKS CONFIGURATIONโ
- Queue: 'thumbnail-render-queue'
- Region: 'europe-central2'
- HTTP Method: POST
- Content-Type: application/json
- Schedule delay: 5 seconds
- Payload: Base64 encoded JSON
7. WORKER COMMUNICATIONโ
The worker receives:
- modelId: ID of the 3D model to render
- templateConfig: Camera configuration from template
- outputWidth/outputHeight: Image dimensions (imageWidth x imageHeight)
- jobId: Unique job ID for tracking
- frontendUrl: Frontend URL for potential callbacks
- reflect: Optional reflective plane setting
- noShadows: Optional shadow rendering setting
8. RESPONSE HANDLINGโ
- Returns 202 Accepted status for successful queueing
- Includes jobId, status ("queued"), and environment-specific message
- Development message: "Rendering request sent to local worker successfully."
- Production message: "Rendering request queued successfully."
- Returns 500 Internal Server Error for failures in task creation or worker communication
9. ERROR HANDLING AND LOGGINGโ
- Comprehensive logging for each phase of the process
- BLOCKING ERROR HANDLING: Firestore save failures immediately terminate execution with 500 error
- Separate error handling for: missing parameters, template not found, Firestore failures, task creation failures
- CRITICAL DEPENDENCY: Job tracking requires successful Firestore save before proceeding
- Detailed payload and response logging for debugging
- Environment detection and URL selection logging
Technical Featuresโ
- PROTOCOL: HTTPS with CORS support
- ARCHITECTURE: Asynchronous processing with immediate response
- QUEUE: Google Cloud Tasks for reliable job processing
- STORAGE: Firestore for job persistence and template configuration
- WORKER: Cloud Run service for actual rendering processing
- UUID: Version 4 for unique job identification
- REGIONS: europe-central2 for optimal performance
- TIMEOUT: No explicit timeout (relies on Cloud Tasks and worker timeouts)
Integrationโ
- Called by: Frontend applications, external APIs
- Input: modelId, templateId, imageWidth, imageHeight, reflect?, noShadows?
- Output: {jobId: string, status: string, message: string}
- Dependencies: Firebase Firestore, Google Cloud Tasks, UUID, Axios (dev), CORS
- Worker Integration: Cloud Run service for actual rendering processing
Input (Payload):โ
{
"modelId": "OV4QJCsmwROVBKXsdqrB",
"templateId": "2gzlELEmDgTJcI10uuAC",
"imageWidth": 1400,
"imageHeight": 628,
"reflect": "true",
"noShadows": "true"
}
Parameters:
modelId(string, required): ID of the document in theVariantscollection containing variant detailstemplateId(string, required): ID of the document in theRenderingTemplatescollection containing rendering template detailsimageWidth(number, required): Width of the rendering image outputimageHeight(number, required): Height of the rendering image outputreflect(string, optional): If equals to"true", a reflective plane is rendered under the scenenoShadows(string, optional): If equals to"true", shadows are not rendered in the output
Output (Success):โ
{
"jobId": "00ea49e1-6b24-4bf3-8f80-091189de8ae7",
"status": "queued",
"message": "Rendering request queued successfully."
}
Response Properties:
jobId(string): UUID v4 ID of the document in theRenderingJobscollection generated by this functionstatus(string): Status of the rendering job (always "queued" for successful requests)message(string): Environment-specific feedback message. Local environment:"Rendering request sent to local worker successfully.", Production environment:"Rendering request queued successfully."
Testingโ
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/createRenderJob
Test with Emulator:
- Start the Firebase emulator:
firebase emulators:start --only functions - Ensure you're using Node.js version 20:
nvm use 20 - Test with curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/createRenderJob" \
-H "Content-Type: application/json" \
-d '{
"modelId": "OV4QJCsmwROVBKXsdqrB",
"templateId": "2gzlELEmDgTJcI10uuAC",
"imageWidth": 1400,
"imageHeight": 628,
"reflect": "true",
"noShadows": "true"
}'
Postman Testing:
- Method: POST
- URL: http://127.0.0.1:5001/arshadesstaging/europe-central2/createRenderJob
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (see examples above)
Deploy Command:โ
firebase deploy --only functions:createRenderJob
Production URL:โ
createRenderJob: https://europe-central2-arshades-7e18a.cloudfunctions.net/createRenderJob
Function Name: createRenderJob
Autore: Gabriele Gilio Data di creazione: 25/09/2025
Last Reviewer: Gabriele Gilio
Trigger: HTTPS (onRequest)
Purpose: Gestisce la creazione di job di rendering per thumbnail 3D validando le richieste, salvandole su Firestore e accodandole tramite Google Cloud Tasks per l'elaborazione asincrona.
Funzionamento Dettagliatoโ
Questa Firebase Function gestisce il flusso completo delle richieste di rendering di thumbnail 3D attraverso un'architettura di elaborazione asincrona:
1. VALIDAZIONE RICHIESTE E GESTIONE CORSโ
- Accetta richieste POST con supporto CORS per chiamate dal frontend
- Valida parametri obbligatori: modelId, templateId, imageWidth, imageHeight
- Parametri opzionali: reflect (booleano come stringa), noShadows (booleano come stringa)
- Restituisce 400 Bad Request per parametri obbligatori mancanti
- Restituisce 405 Method Not Allowed per richieste non-POST
2. GENERAZIONE ID JOB E SALVATAGGIO FIRESTOREโ
- Genera ID job univoco usando UUID v4
- Crea documento nella collezione 'RenderingJobs' con:
- status: "queued"
- createdAt: timestamp ISO
- modelId: ID modello fornito
- templateId: ID template fornito
- imageWidth: larghezza fornita
- imageHeight: altezza fornita
- CRITICO: Se il salvataggio su Firestore fallisce, l'esecuzione viene immediatamente terminata con errore 500
- Restituisce messaggio di errore: "Unable to save the rendering job in the database. Try again later."
- Registra i dettagli relativi alla creazione di job per il debug e il monitoraggio
3. RECUPERO CONFIGURAZIONE TEMPLATEโ
- Recupera documento template dalla collezione 'RenderingTemplates' usando templateId
- Restituisce errore 404 se template non trovato
- Estrae e trasforma dati template nel formato per il worker:
- camera_fov: da fieldOfView
- camera_position: da cameraPosition
- camera_rotation: da cameraRotation
- camera_look_at: da cameraLookAt
- view_name: da viewName
- light_exposition: da lightExposition (default: 1)
4. PREPARAZIONE PAYLOADโ
- Crea payload base con: modelId, templateConfig, outputWidth, outputHeight, jobId, frontendUrl
- Aggiunge condizionalmente parametri reflect e noShadows se forniti
- Imposta frontendUrl per ambiente staging: "https://ars-renderer-staging.web.app/Renderer"
5. ELABORAZIONE SPECIFICA PER AMBIENTEโ
Ambiente di Sviluppo (Emulatore Locale):
- Effettua richiesta HTTP diretta al worker locale su "http://127.0.0.1:8080/process-render"
- Usa axios per elaborazione immediata senza accodamento
- Fornisce feedback immediato sulla risposta del worker
- Restituisce errore se la richiesta HTTP fallisce
Ambiente di Produzione (Staging/Produzione):
- Crea task Google Cloud Tasks per elaborazione asincrona
- Accoda task in 'thumbnail-render-queue' nella regione 'europe-central2'
- Programma esecuzione task 5 secondi dopo la creazione
- URL Worker:
- Codifica payload in base64 per trasmissione Cloud Tasks
6. CONFIGURAZIONE CLOUD TASKSโ
- Coda: 'thumbnail-render-queue'
- Regione: 'europe-central2'
- Metodo HTTP: POST
- Content-Type: application/json
- Ritardo schedulazione: 5 secondi
- Payload: JSON codificato in base64
7. COMUNICAZIONE CON WORKERโ
Il worker riceve:
- modelId: ID del modello 3D da renderizzare
- templateConfig: Configurazione camera dal template
- outputWidth/outputHeight: Dimensioni immagine (imageWidth x imageHeight)
- jobId: ID job univoco per tracking
- frontendUrl: URL frontend per potenziali callback
- reflect: Impostazione opzionale piano riflettente
- noShadows: Impostazione opzionale rendering ombre
8. GESTIONE RISPOSTAโ
- Restituisce status 202 Accepted per accodamento riuscito
- Include jobId, status ("queued"), e messaggio specifico per ambiente
- Messaggio sviluppo: "Rendering request sent to local worker successfully."
- Messaggio produzione: "Rendering request queued successfully."
- Restituisce 500 Internal Server Error per fallimenti nella creazione task o comunicazione worker
9. GESTIONE ERRORI E LOGGINGโ
- Logging completo per ogni fase del processo
- GESTIONE ERRORI BLOCCANTE: I fallimenti di salvataggio su Firestore terminano immediatamente l'esecuzione con errore 500
- Gestione errori separata per: parametri mancanti, template non trovato, fallimenti Firestore, fallimenti creazione task
- DIPENDENZA CRITICA: Il tracking del job richiede un salvataggio su Firestore riuscito prima di procedere
- Logging dettagliato di payload e risposte per debugging
- Logging di rilevamento ambiente e selezione URL
Caratteristiche Tecnicheโ
- PROTOCOLLO: HTTPS con supporto CORS
- ARCHITETTURA: Elaborazione asincrona con risposta immediata
- CODA: Google Cloud Tasks per elaborazione job affidabile
- STORAGE: Firestore per persistenza job e configurazione template
- WORKER: Servizio Cloud Run per elaborazione rendering effettiva
- UUID: Versione 4 per identificazione job univoca
- REGIONI: europe-central2 per performance ottimali
- TIMEOUT: Nessun timeout esplicito (si basa su timeout Cloud Tasks e worker)
Integrazioneโ
- Chiamato da: Applicazioni frontend, API esterne
- Input: modelId, templateId, imageWidth, imageHeight, reflect?, noShadows?
- Output: {jobId: string, status: string, message: string}
- Dipendenze: Firebase Firestore, Google Cloud Tasks, UUID, Axios (dev), CORS
- Integrazione Worker: Servizio Cloud Run per elaborazione rendering effettiva
Input (Payload):โ
{
"modelId": "OV4QJCsmwROVBKXsdqrB",
"templateId": "2gzlELEmDgTJcI10uuAC",
"imageWidth": 1400,
"imageHeight": 628,
"reflect": "true",
"noShadows": "true"
}
Parametri:
modelId(string, richiesto): ID del documento nella collezioneVariantscontenente i dettagli della variantetemplateId(string, richiesto): ID del documento nella collezioneRenderingTemplatescontenente i dettagli del template di renderingimageWidth(number, richiesto): Larghezza dell'immagine di outputimageHeight(number, richiesto): Altezza dell'immagine di outputreflect(string, opzionale): Se uguale a"true", viene renderizzato un piano riflettente sotto la scenanoShadows(string, opzionale): Se uguale a"true", le ombre non vengono renderizzate nell'output
Output (Success):โ
{
"jobId": "00ea49e1-6b24-4bf3-8f80-091189de8ae7",
"status": "queued",
"message": "Rendering request queued successfully."
}
Proprietร della Risposta:
jobId(string): ID UUID v4 del documento nella collezioneRenderingJobsgenerato da questa funzionestatus(string): Stato del job di rendering (sempre "queued" per richieste riuscite)message(string): Messaggio di feedback specifico per ambiente. Ambiente locale:"Rendering request sent to local worker successfully.", Ambiente produzione:"Rendering request queued successfully."
Testingโ
URL (se HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/createRenderJob
Test con Emulatore:
- Avvia l'emulatore Firebase:
firebase emulators:start --only functions - Assicurati di usare Node.js versione 20:
nvm use 20 - Test con curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/createRenderJob" \
-H "Content-Type: application/json" \
-d '{
"modelId": "OV4QJCsmwROVBKXsdqrB",
"templateId": "2gzlELEmDgTJcI10uuAC",
"imageWidth": 1400,
"imageHeight": 628,
"reflect": "true",
"noShadows": "true"
}'
Test con Postman:
- Metodo: POST
- URL: http://127.0.0.1:5001/arshadesstaging/europe-central2/createRenderJob
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (vedi esempi sopra)
Deploy Command:โ
firebase deploy --only functions:createRenderJob
URL di Produzione:โ
createRenderJob: https://europe-central2-arshades-7e18a.cloudfunctions.net/createRenderJob